package com.ssm.web.config.exception;

import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 对于 404 这样不会进入控制器的错误进行处理，spring 对于 404 会跳转到 /error
 */
@RestController
public class GlobalErrorHandler extends BasicErrorController {

    /**
     * 除 web 页面外的错误处理，比如 json/xml 等
     */
    //@RequestMapping(ERROR_PATH)
    //public Map<String, Object> error1(HttpServletRequest request) {
    //    Map<String, Object> errorMap = getErrorAttributes(new ServletWebRequest(request), false);
    //    return errorMap;
    //}

    /**
     * web页面错误处理
     */
    //@RequestMapping(value = ERROR_PATH, produces = "text/html")
    //public Map<String, Object> errorPageHandler(HttpServletRequest request) {
    //    Map<String, Object> errorMap = getErrorAttributes(new ServletWebRequest(request), false);
    //    return errorMap;
    //}
    public GlobalErrorHandler(ErrorAttributes errorAttributes, ServerProperties serverProperties) {
        super(errorAttributes, serverProperties.getError());
    }

    @RequestMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> errorJson(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL));
        body.put("myErrorType", "this is my diy error");
        return new ResponseEntity<>(body, status);
    }
}
